'use strict';
var express = require('express');
var appApi = require('./app-api');
var rewrite = require('express-urlrewrite');
var promiseRequest = require('promise-request');
var {
  fetch
} = require("tiny-fetch");
var config = require('./../../config');
var {
  OrderListNedb, StoreNedb
} = require("./../services/businessNedb");
var {
  Response
} = require("./../services/Response");
var {
  cdcLogger, uncaughtExceptionLogger
} = require("./../services/log");
var taskManage = require("./../services/taskManage")
var {
  getInfo, formatTime
} = require("./../services/utils")
const {
  payingTask, paidTask, noticedTask
} = require("./../services/wechatFastTasks")
const {
  cancelOrderToFbs, refundOrderToFbs, refundOrderToApp, notifyOrderToCns
} = require("./../services/requestService")



const appUrl = config.app.appUrl;
const cdcUrl = config.app.cdcUrl;
const orderExpiration = config.app.orderExpiration;

process.on('uncaughtException', function(err) {
  console.error(err.stack || err);
});
var router = require("express-generator-router")({
  errorhandler: function(res) {
    return function(e) {
      let error;
      if (e.custom) {
        error = Response(500, "业务错误", {
          error: e,
          info: getInfo(res.req, res),
          options: e.options
        })
        cdcLogger.error(error);
      } else {
        error = Response(400, "未知错误", {
          error: e.stack || e.message || e.statusMessage || e.statusCode ||
            e,
          info: getInfo(res.req, res),
          options: e.options
        });
        uncaughtExceptionLogger.error(error);
      }
      return res.json(error);
    }
  }
});

var pay = require('./pay');


module.exports = function(app) {

  app.use('/api/cdc', router.router);

  pay(router);

  router.post('/order/ordering', function*(req, res, next) {
    let data = {}
    data = req.body;
    data.creator = {
      id: "weborder-customer",
      name: "顾客扫码点单"
    }
    const CurrentSerialNo = yield StoreNedb.getSerialNo(data.storeId);
    data.serialNo = "" + CurrentSerialNo;
    let result = yield fetch(
      cdcUrl + '/order/fastOrdering', {
        method: 'POST',
        body: data,
        headers: {
          token: "5429ca08df50392c974c5e71b8db12ab"
        }
      })
    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    res.json(result.data);
  });

  router.post('/order/checkoutOfFastOrder', function*(req, res, next) {

    let result = {};
    result = yield fetch(
      cdcUrl + '/order/checkout', {
        method: 'PUT',
        body: req.body,
        headers: {
          token: "5429ca08df50392c974c5e71b8db12ab"
        }
      })
    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    res.json(result.data);
  });



  router.post('/wechat/openid', function*(req, res, next) {

    var appid, appsecret;
    var storeInfo = yield StoreNedb.getStoreInfo(req.body.storeId);
    appid = storeInfo.appid;
    appsecret = storeInfo.appsecret;
    // appid = "wxeaff9927b76410d8"; //debug
    // appsecret = "82847fab6519ed7e7c6cc6cc978fdae2"; //debug
    let config = {
      scheme: 'https',
      host: 'api.weixin.qq.com',
      path: '/sns/oauth2/access_token?appid=' + appid +
        '&secret=' + appsecret + '&code=' +
        req.body.code + '&grant_type=authorization_code',
      method: 'GET'
    };

    let result = yield promiseRequest(config);
    //mock
    if (result.data.openid) {
      result.data = {
        openid: result.data.openid
      }
      res.json(Response(200, "获取openid成功", result.data));
    } else {
      result.data.custom = true;
      throw result.data;
    }
  })


  router.post('/order/getOrderList', function*(req, res, next) {
    req.body.orderStatus = ["closed", "refund"];
    // durativeTime
    req.body.startTime = new Date().getTime() - 24 * 60 * 60000;
    req.body.endTime = new Date().getTime();
    let result = yield fetch(
      cdcUrl + '/order/getOrder/', {
        method: 'PUT',
        body: req.body
      });
    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    let orderList = result.data.data.filter(function(v) {
      if (v.status != "settled") {
        const _detailOrdered = {
          "statusType": "wx-fast",
          "status": "ordered",
          "createTime": v.closeTime || v.createTime
        }
        v.processStatus = v.processStatus || {};
        v.processStatus.detail = v.processStatus.detail || [];
        v.processStatus.detail.unshift(_detailOrdered);
        return true;
      } else if (v.status == "settled" && v.checkout.payments && v.checkout
        .payments.length >
        0) {
        const _detailQuery = {
          "statusType": "wx-fast",
          "status": "query",
          "createTime": v.checkout.payments[0].createTime
        }
        v.closeTime = v.closeTime || v.createTime;
        v.processStatus = v.processStatus || {};
        v.processStatus.detail = v.processStatus.detail || [];
        v.processStatus.detail.unshift(_detailQuery);
        return true;
      } else {
        return false;
      }
    })
    orderList.sort(
      function sortNumber(a, b) {
        return b.createTime - a.createTime;
      }
    )
    return res.json(Response(200, "查询成功", orderList));

  })

  router.get('/order/:orderId/wechat', function*(req, res, next) {
    let result = yield fetch(config.app.cdcUrl + '/order/getOrderById/' +
      req.params.orderId);
    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    if (result.data.data && result.data.data.processStatus &&
      result.data.data.processStatus
      .status == "received") {
      return res.json(Response(201, "消息已通知成功", result.data.data))
    }
    let data = {
      storeId: result.data.data.storeId,
      orderId: result.data.data.id,
      wechatOrderId: ""
    }
    const payOrder = yield fetch(
        config.app.app + "/api/wechatpay/queryPay", {
          method: 'POST',
          body: data
        })
      //已经退款
    if (payOrder.data && payOrder.data.scanPayResData && payOrder.data.scanPayResData
      .result_code ==
      "SUCCESS" &&
      payOrder.data.scanPayResData.trade_state == "SUCCESS") {
      res.json(Response(200, "订单查询成功", payOrder.data));
    } else {
      res.json(Response(500, "订单查询失败", payOrder.data));
    }

  })


  router.post('/pos/message', function*(req, res, next) {
    // return res.json(Response(200)); //debugger
    let result;
    taskManage.removeTaskByOrderId(req.body.order.id);
    result = yield fetch(
      cdcUrl + '/order/closeOrder', {
        method: 'PUT',
        body: {
          orderNo: req.body.order.id,
          processStatus: "received",
          lastPrintTime: req.body.lastPrintTime
        },
        headers: {
          token: "5429ca08df50392c974c5e71b8db12ab"
        }
      })

    if (result.data.code != 200) {
      result.data.custom = true;
      throw result.data;
    }
    res.json(result.data);
  })

  router.get('/order/:orderId/fbs', function*(req, res, next) {
    let result = yield fetch(cdcUrl + '/order/getOrderById/' + req.params
      .orderId);
    res.json(result.data);
  })

  router.get('/stores/:storeId/wxinit', function*(req, res, next) {
    // req.params.tableId
    req.appApi = appApi(req.params.storeId);
    let result = yield req.appApi.get("/wxinit");
    res.json(result.data);
  })

  router.get('/test', function*(req, res, next) {
    req.appApi = appApi(req.body.storeId);
    let result = yield req.appApi.get("wxinit");
    console.log(result.data);
  })



}
